// cloudfunctions/syncGameRecord/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-3gew2xhnadfbd1bd'
})

const db = cloud.database()
const _ = db.command

/**
 * 同步游戏记录云函数
 * 功能：
 * 1. 保存游戏记录到云端
 * 2. 更新用户统计数据
 * 3. 计算经验值和等级
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID
  
  try {
    const { gameRecord } = event
    
    if (!gameRecord) {
      return {
        success: false,
        error: '缺少游戏记录数据'
      }
    }
    
    // 保存游戏记录
    const recordData = {
      _openid: openId,
      timestamp: gameRecord.timestamp || Date.now(),
      duration: gameRecord.duration,
      steps: gameRecord.steps,
      backtracks: gameRecord.backtracks,
      success: gameRecord.success,
      solveType: gameRecord.solveType, // 'manual' 或 'auto'
      difficulty: gameRecord.difficulty, // 'easy', 'medium', 'hard'
      createTime: new Date()
    }
    
    const addResult = await db.collection('game_records').add({
      data: recordData
    })
    
    // 更新用户统计
    const userQuery = await db.collection('users').where({
      _openid: openId
    }).get()
    
    if (userQuery.data.length > 0) {
      const user = userQuery.data[0]
      
      // 计算经验值
      let expGain = 0
      if (gameRecord.success) {
        // 根据难度和完成方式给经验
        const difficultyExp = {
          'easy': 10,
          'medium': 20,
          'hard': 30
        }
        const typeMultiplier = gameRecord.solveType === 'manual' ? 2 : 1
        expGain = (difficultyExp[gameRecord.difficulty] || 10) * typeMultiplier
      }
      
      const newExp = (user.experience || 0) + expGain
      const newLevel = Math.floor(newExp / 100) + 1 // 每100经验升1级
      
      // 更新用户数据
      await db.collection('users').doc(user._id).update({
        data: {
          totalGames: _.inc(1),
          totalWins: gameRecord.success ? _.inc(1) : user.totalWins,
          totalPlayTime: _.inc(gameRecord.duration || 0),
          experience: newExp,
          level: newLevel,
          updateTime: new Date()
        }
      })
      
      return {
        success: true,
        data: {
          recordId: addResult._id,
          expGain: expGain,
          newExp: newExp,
          newLevel: newLevel,
          levelUp: newLevel > (user.level || 1)
        }
      }
    } else {
      return {
        success: true,
        data: {
          recordId: addResult._id,
          message: '记录已保存，但用户信息未更新'
        }
      }
    }
  } catch (err) {
    console.error('同步游戏记录失败:', err)
    return {
      success: false,
      error: err.message
    }
  }
}
